package com.google.common.io;

import com.google.common.base.Preconditions;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public final class Files {

    private static final class FileByteSource extends ByteSource {
        private final File file;

        private FileByteSource(File file) {
            this.file = (File) Preconditions.checkNotNull(file);
        }

        public FileInputStream openStream() throws IOException {
            return new FileInputStream(this.file);
        }

        public byte[] read() throws IOException {
            long size = this.file.length();
            if (size == 0) {
                return super.read();
            }
            if (size > 2147483647L) {
                throw new OutOfMemoryError("file is too large to fit in a byte array: " + size + " bytes");
            }
            byte[] bytes = new byte[((int) size)];
            Closer closer = Closer.create();
            try {
                InputStream in = (InputStream) closer.register(openStream());
                int off = 0;
                int read = 0;
                while (((long) off) < size) {
                    read = in.read(bytes, off, ((int) size) - off);
                    if (read == -1) {
                        break;
                    }
                    off += read;
                }
                byte[] result = bytes;
                if (((long) off) < size) {
                    result = Arrays.copyOf(bytes, off);
                } else if (read != -1) {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    ByteStreams.copy(in, out);
                    byte[] moreBytes = out.toByteArray();
                    result = new byte[(bytes.length + moreBytes.length)];
                    System.arraycopy(bytes, 0, result, 0, bytes.length);
                    System.arraycopy(moreBytes, 0, result, bytes.length, moreBytes.length);
                }
                closer.close();
                return result;
            } catch (Throwable th) {
                closer.close();
            }
        }

        public String toString() {
            return "Files.asByteSource(" + this.file + ")";
        }
    }

    public static ByteSource asByteSource(File file) {
        return new FileByteSource(file);
    }

    public static byte[] toByteArray(File file) throws IOException {
        return asByteSource(file).read();
    }
}
